﻿Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.IO
Public Class Receive
    Public Shared networkStream As NetworkStream
    Public Shared MessageReader As StreamReader
    Public Event ThreadComplete(ByVal MessageReceived As String)
    Dim ReceivedQueue As New Queue

    Public Sub Receive()
        Try
            Do
                If BNetworking.T.Connected = False Then
                    Exit Sub
                End If
                networkStream = BNetworking.T.GetStream()
                ' Read the stream into a byte array
                Dim bytes(BNetworking.T.ReceiveBufferSize) As Byte
                networkStream.Read(bytes, 0, CInt(BNetworking.T.ReceiveBufferSize))
                Dim Message As String = Encoding.ASCII.GetString(bytes)
                If Message <> "" Then
                    Dim Messages() As String = Message.Split(Chr(13))
                    Dim MessagesNumber As Integer = Messages.Length()
                    Dim MsgNo As Integer = 0
                    While MessagesNumber > 0
                        RaiseEvent ThreadComplete(Messages(MsgNo))
                        MessagesNumber = MessagesNumber - 1
                        MsgNo = MsgNo + 1
                    End While
                    'ReceivedQueue.Enqueue(Message)
                    'MainForm.t2 = New Thread(AddressOf Process)
                    'MainForm.t2.Priority = ThreadPriority.Highest
                    'MainForm.t2.Start(Message)
                End If
            Loop
        Catch ex As Exception
            Console.WriteLine("RECEIVE FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Public Sub Process(ByVal Message As String)
        Try
            If Message <> "" Then
                Dim Messages() As String = Message.Split(Chr(13))
                Dim MessagesNumber As Integer = Messages.Length()
                Dim MsgNo As Integer = 0
                While MessagesNumber > 0
                    RaiseEvent ThreadComplete(Messages(MsgNo))
                    MessagesNumber = MessagesNumber - 1
                    MsgNo = MsgNo + 1
                End While
                'ReceivedQueue.Dequeue()
            End If
        Catch ex As Exception
            Console.WriteLine("PROCESS FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub
End Class